
package org.codebase.hadoop.zookeeper.cluster;

import java.io.IOException;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

/**
 * 客户端程序
 **************************************************
 * ClassName:ClusterClient

 * @author:xiaozhichao
 * @date:2018年8月18日
 **************************************************
 */
public class ClusterClient implements Watcher, Runnable {

	private ZooKeeper zk;
	
	public ClusterClient(String hostPort, Long pid,String root) {
		String processId = pid.toString();
		try {
			zk = new ZooKeeper(hostPort,2000,this);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(zk != null){
			try {
				zk.create(root + "/" + processId, processId.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
			} catch (KeeperException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public void process(WatchedEvent event) {
		System.out.printf("\nEvent Received: %s", event.toString());
		
	}

	@Override
	public void run() {
		try{
			synchronized (this) {
				while(true){
					wait();
				}
			}
		}catch(Exception e){
			Thread.currentThread().interrupt();
		}finally{
			try {
				zk.close();
			} catch (InterruptedException e) {
				e.printStackTrace();
					
			}
		}
			
	}

}
